from scavenger import Scavenger
from time import sleep

# Initialise Scavenger and start listening for surrogates.
s = Scavenger() 

# An example of manual remoting.
# 1) Wait for a surrogate to show up.
surrogates = s.get_peers()
while len(surrogates) == 0:
    sleep(0.1)
    surrogates = s.get_peers()
surrogate = surrogates[0] # We simply pick the first surrogate.

# 2) Check that the desired service is installed on the surrogate.
if not s.has_service(surrogate, 'daimi.test.subtract'):
    # The service does not exist - install it.
    s.install_service(surrogate, 'daimi.test.subtract', """
def perform(x, y):
    return x-y    
""")

# 3) Perform the service.
result = s.perform_service(surrogate, 'daimi.test.subtract', {'x':17, 'y':12})
#print result


# An example of automated remoting.
result = s.scavenge('daimi.test.subtract', {'x':17, 'y':12}, """
def perform(x, y):
    return x-y    
""", lambda x, y: x-y)
#print result

# The last two arguments are optional. If no surrogates are available, 
# or if none have the service installed a ScavengerException is thrown.
result = s.scavenge('daimi.test.subtract', {'x':17, 'y':12})
#print result

s.shutdown()
